//
//  MainTabBarController.m
//  PASystem
//
//  Created by michael on 16/7/19.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "shangjiaViewController.h"
#import "lianxixinViewController.h"
#import "zhaocanpinViewController.h"
#import "OALoginViewController.h"
#import "jinrongViewController.h"
#import "rongziViewController.h"
#import "myViewController.h"
#import "OAAddressViewController.h"
#import "buttonitem.h"
#import "UIViewController+MMDrawerController.h"
#import "MMDrawerBarButtonItem.h"
#import "MainTabBarController.h"
#import "buttonitem.h"
#import "MainViewController.h"
#import "ViewController2.h"
#import "ViewController3.h"
#import "OABaseNavViewController.h"
#import "jinrongViewController.h"
#import "rongziViewController.h"
#import "myViewController.h"
#import "TBTabBar.h"
@interface MainTabBarController ()

@end

@implementation MainTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *images =  @[[UIImage imageNamed:@"1、宣传页面-1（750x1334）"],[UIImage imageNamed:@"1、宣传页面-2（750x1334）"],[UIImage imageNamed:@"1、宣传页面-3（750x1334）"]];
    //创建引导页视图
    ZLCGuidePageView *pageView = [[ZLCGuidePageView alloc]initWithFrame:self.view.frame WithImages:images];

    if (![[DanLi sharedDanLi].value isEqualToString:@"no"]) {
//            [self.view addSubview:pageView];

}
//        [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];

        self.tabBar.tintColor = [UIColor colorWithHexString:@"f03ff5"];
//        COLORRGB(0xf03ff5);
//        [self _initViewControllers];
//
//    [self _customTabar];
  //2、添加双击手势
//    UITapGestureRecognizer * doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
    //2.1、双击
//    [doubleTap setNumberOfTapsRequired:2];
//    [self.view addGestureRecognizer:doubleTap];
    
    //3、添加两个手指双击手势
//    UITapGestureRecognizer * twoFingerDoubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(twoFingerDoubleTap:)];
//    //3.1、双击
//    [twoFingerDoubleTap setNumberOfTapsRequired:2];
//    //3.2、两个手指  默认为一个
//    [twoFingerDoubleTap setNumberOfTouchesRequired:2];
//    [self.view addGestureRecognizer:twoFingerDoubleTap];

    // Do any additional setup after loading the view.
        [self setUpChildVC];

}
#pragma mark -初始化所有控制器

- (void)setUpChildVC {

    MainViewController *homeVC = [[MainViewController alloc] init];
//    homeVC.tabBarItem.badgeValue = @"1111";
    [self setChildVC:homeVC title:NSLocalizedString(@"首页", nil) image:@"首页-默认" selectedImage:@"首页-选中"];
    
//    jinrongViewController *fishpidVC = [[jinrongViewController alloc] init];
shangjiaViewController * fishpidVC = [[shangjiaViewController alloc]init];
    [self setChildVC:fishpidVC title:NSLocalizedString(@"商家", nil) image:@"商家-默认" selectedImage:@"商家-选中"];
    
//    rongziViewController *messageVC = [[rongziViewController alloc] init];
        lianxixinViewController *messageVC = [[lianxixinViewController alloc] init];

    [self setChildVC:messageVC title:NSLocalizedString(@"联系信", nil) image:@"联系信-默认" selectedImage:@"联系信-选中"];
    
    myViewController *myVC = [[myViewController alloc] init];
//[[UITabBar appearance] setBarTintColor:COLORRGB(0xf03ff5)];
   [self setChildVC:myVC title:NSLocalizedString(@"我的", nil) image:@"我的-默认" selectedImage:@"我的-选中"];

}

- (void) setChildVC:(UIViewController *)childVC title:(NSString *) title image:(NSString *) image selectedImage:(NSString *) selectedImage {
    
    childVC.tabBarItem.title = title;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"484848"];
    dict[NSFontAttributeName] = [UIFont systemFontOfSize:10];
    [childVC.tabBarItem setTitleTextAttributes:dict forState:UIControlStateNormal];
      NSMutableDictionary *dict2 = [NSMutableDictionary dictionary];
    dict2[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"0a62ea"];
        [childVC.tabBarItem setTitleTextAttributes:dict2 forState:UIControlStateSelected];

    childVC.tabBarItem.image = [[UIImage imageNamed:image] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVC.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:childVC];
    [self addChildViewController:nav];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    NSArray *imageNames = @[NSLocalizedString(@"首页", nil),NSLocalizedString(@"商家", nil),NSLocalizedString(@"联系信", nil),NSLocalizedString(@"我的", nil)];
   NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"language"];


    NSLog(@"item name = %@", item.title);

    NSInteger index = [self.tabBar.items indexOfObject:item];
   
//    [self animationWithIndex:index];
//[item setTitle:imageNames[index]];
    if([item.title isEqualToString:NSLocalizedString(@"我的", nil)]){
    
      [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
    
    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"autoLogin"]isEqualToString:@"Y"]&&![[DanLi sharedDanLi].stay isEqualToString:@"yes"]) {
      OALoginViewController * loginVC = [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        loginVC.navigationController.navigationBar.hidden = YES;
                 self.view.window.rootViewController = navVC;

}
   }
   
    if([item.title isEqualToString:NSLocalizedString(@"联系信", nil)]){
    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"autoLogin"]isEqualToString:@"Y"]&&![[DanLi sharedDanLi].stay isEqualToString:@"yes"]) {
      OALoginViewController * loginVC = [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        loginVC.navigationController.navigationBar.hidden = YES;
                 self.view.window.rootViewController = navVC;

}
   }
    
//   if (index ==3) {
//  if([language isEqualToString:@"1"]){
//  [item setTitle:@"My"];
//
//}
//}
}
- (void)animationWithIndex:(NSInteger) index {
    NSMutableArray * tabbarbuttonArray = [NSMutableArray array];
    for (UIView *tabBarButton in self.tabBar.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabbarbuttonArray addObject:tabBarButton];
        }
    }
    CABasicAnimation*pulse = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulse.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pulse.duration = 0.2;
    pulse.repeatCount= 1;
    pulse.autoreverses= YES;
    pulse.fromValue= [NSNumber numberWithFloat:0.7];
    pulse.toValue= [NSNumber numberWithFloat:1.3];
    [[tabbarbuttonArray[index] layer]
     addAnimation:pulse forKey:nil];
}
//-(void)doubleTap:(UITapGestureRecognizer*)gesture{
//    [self.mm_drawerController bouncePreviewForDrawerSide:MMDrawerSideLeft completion:nil];
//}

/**
 *  添加点击手势  两个个手指双击
 */
//-(void)twoFingerDoubleTap:(UITapGestureRecognizer*)gesture{
//    [self.mm_drawerController bouncePreviewForDrawerSide:MMDrawerSideRight completion:nil];
//}

+ (NSString *)currentDateWithFormat:(NSString *)format{


NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"MMM d, yyyy HH:mm:ss aa";
 fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
     NSDate *date = [fmt dateFromString:format];
     NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    fm.dateFormat = @"yyyy-MM-dd";
     NSString *selfYear = [fm stringFromDate:date];
   return selfYear;




  }
//01创建所有的子视图控制器
- (void)_initViewControllers{
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

//      MainViewController * mainVC = [storyBoard instantiateViewControllerWithIdentifier:@"MainVC"];
MainViewController * mainVC = [[MainViewController alloc]init];
         OAAddressViewController * readvc = (OAAddressViewController*)[storyBoard  instantiateViewControllerWithIdentifier:@"AddressVCID"];

//          ViewController2 *readvc = [[ViewController2 alloc]init];
    ViewController3 *lisvc = [[ViewController3 alloc]init];
        NSArray *viewCtrls = @[mainVC,readvc,lisvc];
    // 创建一个可变数组存放所有的导航控制器
   _navCtrls = [[NSMutableArray alloc] init];

    
    for (UIViewController *viewCtrl in viewCtrls) {
        // 创建导航控制器
        OABaseNavViewController *baseNavCtrl = [[OABaseNavViewController alloc] initWithRootViewController:viewCtrl];
        baseNavCtrl.delegate = self;
        
        // 导航控制器添加到数组中
        [_navCtrls addObject:baseNavCtrl];
        
    }
    self.viewControllers = _navCtrls;

}
    

             
             
//02 定制标签栏
- (void)_customTabar
{
    // 1 影藏
//    self.tabBar.translucent = NO;

    self.tabBar.hidden=YES;
    // 2 创建自定义标签视图，选中标签栏选项视图
    _tabBarImageview =  [[UIImageView alloc]initWithFrame:CGRectMake(0, kScreenHeight-49, kScreenWidth, 49)];
    UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];

    _tabBarImageview.backgroundColor = myColor;
//self.tabBar.backgroundColor =myColor;
//[_tabBarImageview setImage:[UIImage imageNamed:@"tar"]];
_tabBarImageview.backgroundColor = [UIColor blueColor];
    _tabBarImageview.userInteractionEnabled = YES;
    [self.view addSubview:_tabBarImageview];

       //3 创建5个按钮
    //tabbar_icon_found_normal@2x.png
    NSArray *imageNames = @[@"首页",@"金融产品推荐",@"申请融资",@"我的"];
    
    

    // 循环创建
    float itemWidth = kScreenWidth / imageNames.count;
    for (int i = 0 ; i < imageNames.count; i++) {
        UIButton *barItem = [[UIButton alloc] initWithFrame:CGRectMake(i * itemWidth, 0, itemWidth, 49)];
        // 设置标题
//        barItem.title = titles[i];
        // 设置图片
        
        [barItem setImage:[UIImage imageNamed:imageNames[i]] forState:UIControlStateNormal];
        NSString *sring = [NSString stringWithFormat:@"%@选中",imageNames[i]];
//    [barItem setImage:[UIImage imageNamed:sring] forState:UIControlStateSelected];
//  barItem.titleLabel.font= [UIFont systemFontOfSize:14];
        [barItem setImageEdgeInsets:UIEdgeInsetsMake(-10,-10, -10, -10)];
//
//        [barItem setTitleEdgeInsets:UIEdgeInsetsMake(20,-20, -20, 20)];
//
//        [barItem setTitle:imageNames[i] forState:UIControlStateNormal];
        // 设置事件
        barItem.tag = 10+i;
        if (barItem.tag==10) {
            [barItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            barItem.selected = YES;
        }
    

        [barItem addTarget:self action:@selector(itemAction:) forControlEvents:UIControlEventTouchUpInside];
        [_tabBarImageview addSubview:barItem];
    }
    //默认选中的中间的控制器
self.selectedIndex = 0;

}
- (void)itemAction:(UIButton *)button{
        self.selectedIndex = button.tag-10;
        if (_index !=self.selectedIndex)
    {
        UIButton *button1 = (UIButton *)[_tabBarImageview viewWithTag:self.selectedIndex+10];
        button1.selected = YES;
        UIButton *button2 = (UIButton *)[_tabBarImageview viewWithTag:_index+10];
        [button2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button2.selected = NO;
    
    }
    if (button.selected) {
        _index = self.selectedIndex;

}

}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
int count = (int)navigationController.viewControllers.count;
    if (count==1) {
    
    viewController.tabBarController.tabBar.hidden =YES;

        _tabBarImageview.hidden = NO;
       
                }
    else {
        viewController.tabBarController.tabBar.hidden =YES;
        //是push进来的视图控制器
        _tabBarImageview.hidden=YES;
//[tabbar setHidden = YES]
    }
}



   
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc{


}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
